<?php

namespace app\api\service;
use Ratchet\ConnectionInterface;

class BroadcastService {
    protected $clients; // 存储连接
    protected $userMap; // 用户 ID 与连接的映射

    public function __construct() {
        $this->clients = new \SplObjectStorage(); // 用于存储连接
        $this->userMap = []; // 存储用户 ID 和连接的映射
    }

    public function addClient(ConnectionInterface $conn, $userId) {
        $this->clients->attach($conn); // 存储新连接
        $this->userMap[$userId] = $conn; // 将用户ID与连接关联
        echo "Client added: {$userId} (connection: {$conn->resourceId})\n"; // Debug output
    }

    public function removeClient(ConnectionInterface $conn) {
        // 找到用户 ID 并移除
        foreach ($this->userMap as $userId => $client) {
            if ($client === $conn) {
                unset($this->userMap[$userId]); // 移除用户 ID
                break;
            }
        }
        $this->clients->detach($conn); // 移除关闭的连接
        echo "Client removed: {$conn->resourceId}\n"; // Debug output
    }

    public function broadcast($message) {
        foreach ($this->clients as $client) {
            // 发送消息给所有连接的客户端
            $client->send($message);
            echo "Broadcasting message: $message to {$client->resourceId}\n"; // Debug output
        }
    }

    public function sendToUserById($targetUserId, $message) {
        // 根据用户 ID 查找并发送消息
        if (isset($this->userMap[$targetUserId])) {
            $client = $this->userMap[$targetUserId];
            $client->send($message);
            echo "Sent message to user: {$targetUserId}, Message: $message\n"; // Debug output
        } else {
            echo "User {$targetUserId} not found for sending message.\n"; // Debug output
        }
    }

    public function getConnectedClients() {
        return iterator_to_array($this->clients); // 返回当前连接的客户端
    }
}
